import Vue from "vue";
import axios from 'axios';
//配置全局处理函数
axios.defaults.timeout = 5000;
let loader=[];
//请求拦截器
axios.interceptors.request.use(function (config) {
    let _loader = Vue.layer.open ({
        content: '加载中...',
        skin: "my-layer-load"
        , type: 3
    });
    loader.push(_loader);
    return config;
}, function (error) {
    closeAll();
    onError(error.toString());
    return Promise.reject(error);
});
//响应拦截器
axios.interceptors.response.use(function (res) {
    closeAll();
    if(res.data.message){
        onError(res.data.message);
        return;
    }
    if(res.status==200){
        return res;
    }
    return res;
}, function (error) {
    closeAll();
    if(!error.response){
        onError('网络异常!');
        return Promise.reject(error); 
    }
    let {status,data} = error.response;
    if(data.message){
        onError(data.message);
        return Promise.reject(error);
    }
    return Promise.reject(status);
});
function onError(message){
    Vue.layer.open({
        content: message
        , skin: 'msg'
        , time: 2 //2秒后自动关闭
    });
}
function http(options) {
    let _options = {};
    return axios(Object.assign(_options, options))
}
function closeAll(){
   for(let lo in loader){
        Vue.layer.close(loader[lo]);
   }
}
Vue.prototype.$http=http;
export default http;

